package com.sum.tea.xinlian

import android.os.Bundle
import android.widget.ArrayAdapter
import androidx.lifecycle.lifecycleScope
import com.blankj.utilcode.util.ToastUtils
import com.function.commfun
import com.sum.common.base.BaseMvvmActivity
import com.sum.tea.contants.AppConfig
import com.sum.tea.databinding.ActivitySubqtlayoutBinding
import com.sum.tea.xinlian.viewmodel.SubQTViewModel
import com.uhf.api.cls.Reader.CustomCmdType
import com.uhf.api.cls.Reader.Mtr_Param
import com.uhf.api.cls.Reader.READER_ERR
import com.uhf.api.cls.Reader.TagFilter_ST
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 特殊指令QT
 *
 * @author Administrator
 */
class SubQTActivity : BaseMvvmActivity<ActivitySubqtlayoutBinding, SubQTViewModel>(){
    private val mAppConfig: AppConfig = AppConfig.getInstance()
    private var g2tfQt: TagFilter_ST? = null

    override fun initView(savedInstanceState: Bundle?) {
        // 初始化 Spinner
        val arradpFbank = ArrayAdapter(this, android.R.layout.simple_spinner_item, AppConfig.spifbank)
        arradpFbank.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        mBinding.spinnerOpfbankQt.adapter = arradpFbank

        // 设置按钮点击事件
        mBinding.buttonQtset.setOnClickListener {
            lifecycleScope.launch {
                try {
                    performOperations()
                    ToastUtils.showShort(AppConfig.Constr_ok)
                } catch (e: Exception) {
                    ToastUtils.showShort("${AppConfig.Constr_excep} ${e.message}")
                }
            }
        }
    }

    private suspend fun performOperations() = withContext(Dispatchers.IO) {
        setOpant()
        setPassword()
        setFilter()

        val rpaswd = ByteArray(4)
        if (mAppConfig.Rparams.password.isNotEmpty()) {
            mAppConfig.Mreader.Str2Hex(
                mAppConfig.Rparams.password,
                mAppConfig.Rparams.password.length,
                rpaswd
            )
        }

        // m4 qt
        val customPara = mAppConfig.Mreader.IMPINJM4QtPara().apply {
            TimeOut = 1000
            CmdType = commfun.SortGroup(mBinding.radioGroupCmdtype)
            if (CmdType == 1) {
                MemType = if (commfun.SortGroup(mBinding.radioGroupView) == 0) 1 else 0
                PersistType = if (commfun.SortGroup(mBinding.radioGroupSta) == 0) 1 else 0
                RangeType = if (commfun.SortGroup(mBinding.radioGroupDic) == 0) 1 else 0
            }
            AccessPwd = rpaswd
        }

        val customRet = mAppConfig.Mreader.IMPINJM4QtResult()
        mAppConfig.Mreader.CustomCmd(
            mAppConfig.Rparams.opant,
            CustomCmdType.IMPINJ_M4_Qt,
            customPara,
            customRet
        )
    }

    private fun setOpant() {
        mAppConfig.Rparams.opant = commfun.SortGroup(mBinding.radioGroupOpantQt) + 1
    }

    private fun setFilter() {
        if (commfun.SortGroup(mBinding.radioGroupEnableopfilQt) == 1) {
            val filterDataInput = mBinding.editTextOpfilterdataQt.text.toString()
            var ln = filterDataInput.length
            if (ln == 1 || ln % 2 == 1) ln++
            val fdata = ByteArray(ln / 2)
            mAppConfig.Mreader.Str2Hex(filterDataInput, filterDataInput.length, fdata)

            g2tfQt = mAppConfig.Mreader.TagFilter_ST().apply {
                this.fdata = fdata
                this.flen = fdata.size * 8
                this.isInvert = if (commfun.SortGroup(mBinding.radioGroupOpmatchQt) == 1) 1 else 0
                this.bank = mBinding.spinnerOpfbankQt.selectedItemPosition + 1
                this.startaddr = mBinding.editTextOpfilsadrQt.text.toString().toInt()
            }

            val er = mAppConfig.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_FILTER, g2tfQt)
            if (er != READER_ERR.MT_OK_ERR) {
                throw Exception(er.toString())
            }
        } else {
            g2tfQt = null
            mAppConfig.Mreader.ParamSet(Mtr_Param.MTR_PARAM_TAG_FILTER, g2tfQt)
        }
    }

    private fun setPassword() {
        mAppConfig.Rparams.password = if (mBinding.checkBoxOpacepwdQt.isChecked) {
            mBinding.editTextPasswordQt.text.toString()
        } else {
            ""
        }
    }
}
